<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="handleDownload"
            >excel导出</el-button
          >
          <el-button type="primary" size="small" @click="showDia = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card v-loading="carLoading" style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column
            label="序号"
            type="index"
            :index="indexMath"
            sortable
          />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column>
            <template #default="{ row }">
              <img
                class="staff"
                :src="row.staffPhoto || daImg"
                alt=""
                @click="qrcodeClick(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatEmploy"
            label="聘用形式"
            sortable
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            sortable
            fixed="right"
            width="280"
          >
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('USER_DEL_ID')"
                @click="delCol(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 3, 5, 7, 10]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 弹出层 -->
        <AddEmployess :show-dialog.sync="showDia" @add-data="getuserDataList" />
        <!-- 弹窗 -->
        <el-dialog
          width="300px"
          title="扫码预览"
          :visible="isShowDia"
          @close="closeDia"
        >
          <el-row type="flex" justify="center">
            <canvas ref="Canvas">扫码预览</canvas>
          </el-row>
        </el-dialog>

        <!-- 角色相关弹窗组件 -->
        <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import AddEmployess from './AddEmployess.vue'
import obj from '@/constant/employees'
import { formatTime } from '@/utils'
import QrCode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
export default {
  name: 'Employees',
  components: {
    AddEmployess,
    AssignRole,
  },
  data() {
    return {
      daImg:
        'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      list: [],
      page: 1,
      pagesize: 5,
      total: 0,
      carLoading: false, // 控制 car loading
      showDia: false, // 控制dialog显隐
      isShowDia: false, // 控制扫码预览
      showRoleDialog: false, // 控制角色相关弹窗
      userId: '', // 点击角色获取的id
    }
  },
  computed: {},
  created() {
    this.getuserDataList()
  },
  methods: {
    checkPermission(key) {
      if (this.$store.getters.roles) {
        // includes是否包含
        return this.$store.getters.roles.points.includes(key)
      } else {
        return false
      }
    },
    // 编辑
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 扫码预览
    qrcodeClick(url) {
      if (!url) return
      this.isShowDia = true
      // （dom对象, 信息载体）  (异步)
      // 所有dom更新完毕
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.Canvas, url)
      })
    },
    // 扫码预览关闭
    closeDia() {
      this.isShowDia = false
    },
    async handleDownload() {
      // 表头数据
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门',
      ]
      // 中英文对照表
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
      }

      // 源数据 [{}{}]
      const {
        data: { rows },
      } = await reqGetEmployeeList(1, this.total)
      // console.log(rows, 44444)

      // 数组对象转化二维数组
      const TwoWeiData = this.transFormTwowei(
        rows,
        headersArr,
        headersRelations
      )
      import('@/vendor/Export2Excel').then((excel) => {
        this.carLoading = true
        console.log(excel, 5555)
        excel.export_json_to_excel({
          // 表格的头部 数组(有序)
          header: headersArr,
          // 表格的主体数据是二维数组
          data: TwoWeiData,
          filename: '员工基本信息', // 导出的文件命名
          autoWidth: true, // 自适应宽度 (非必填)
          bookType: 'xlsx', // 文件类型  （非必填）
        })
        this.carLoading = false
      })
    },
    transFormTwowei(rows, headersArr, headersRelations) {
      const arr = []
      // 源数据决定外层数组数量
      rows.forEach((item) => {
        const res = []
        // 表头限制每个数组长度
        headersArr.forEach((v) => {
          const engLishkey = headersRelations[v]
          let value = item[engLishkey]
          // 时间时期过滤
          if (['timeOfEntry', 'correctionTime'].includes(engLishkey)) {
            value = formatTime(value)
          }

          // 聘用形式过渡
          if (engLishkey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find((item) => item.id === value)
            resObj ? resObj.value : '未知'
          }
          res.push(value)
        })

        arr.push(res)
      })
      return arr
    },
    // 自定义序号
    indexMath(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 聘用属性过滤
    formatEmploy(row, column, cellValue, index) {
      const res = obj.hireType.find((item) => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    // 根据id删除数据
    delCol(id) {
      this.$confirm('此乃高危操作！汝可知！', '温馨提醒')
        .then(async () => {
          const { success, message } = await reqDelEmployee(id)
          // 删除当前页没数据时,自退一页
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          if (!success) return
          this.$message.success(message)
          // 重新刷新数据
          this.getuserDataList()
        })
        .catch(() => {
          this.$message.error('取消删除操作')
        })
    },
    // 当前页
    handleCurrentChange(val) {
      this.page = val
      this.getuserDataList()
    },
    // 每页多少条数据
    handleSizeChange(val) {
      // console.log(val, '每页多少条数据')
      this.pagesize = val
      this.getuserDataList()
    },
    // 获取员工列表数据
    async getuserDataList() {
      this.carLoading = true
      const {
        data: { rows, total },
      } = await reqGetEmployeeList(this.page, this.pagesize)
      this.list = rows
      this.total = total
      this.carLoading = false
    },
  },
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
